<?php
/**
 * Created by PhpStorm.
 * User: frankpian
 * Date: 17-12-6
 * Time: 下午5:14
 */

use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Between;
use Phalcon\Validation\Validator\StringLength;

class ZoneController extends CloudControllerBase
{

    public function noflyTaskAction(){
        if($this->isMonitorAdminUser()){
            $this->view->setVars(array("show_approve" => true));
        }
    }

    public function noFlyZoneDemoAction()
    {

    }

    public function getNoFlyZoneAction()
    {
        $max["lng"] = $this->getPost("maxLng");
        $max["lat"] = $this->getPost("maxLat");
        $min["lng"] = $this->getPost("minLng");
        $min["lat"] = $this->getPost("minLat");
        $distance = $this->getLngLatDistance($max, $min);
        if ($distance>710){
            $this->returnError("Too far away");
        }
        $sql = "SELECT n.* FROM no_fly_zone AS n
            WHERE enable=1 and n.lat< " . $max["lat"] . " AND n.lat> " .  $min["lat"] . " AND n.lng< " . $max["lng"] . " AND n.lng> " . $min["lng"];
        $data = $this->fetchAll($sql);

        return $this->returnJson($data);

    }

    public function getLiftNoFlyZoneAction()
    {
        $userId = $this->getMonitorLoginUser()->userId;
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_LIST: {
                $tableName = "(SELECT * FROM lift_no_fly_zone
                    WHERE applyUser_id=$userId)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "created_at" => "申请日期",
                    "name" => "申请项目名称",
                    "explain_text" => "说明",
                    "status" => "审批状态",
                    "notes" => "审批说明"
                ), $tableName, array(
                    ["name", "like", "%", "%"],
                    ["notes", "like", "%", "%"],
                    ["status", "=", "", ""],
                    ["created_at_start", ">=", "", "", "created_at"],
                    ["created_at_end", "<=", "", "", "created_at"],
                ), "created_at desc", "id");
            };
                break;
            case $this::REQUEST_ACTION_DETAIL: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "请求参数错误"),
                ));
                $keyId = $this->getPost("id");
                $sql = "SELECT * FROM lift_no_fly_zone WHERE id=$keyId";
                $keyData = $this->fetchOne($sql);
                $this->returnJson($keyData);
            };
                break;
            case $this::REQUEST_ACTION_ADD: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "name",
                        "type" => "presence",
                        "message" => "申请项目名称为空",
                    ),
                    array(
                        "key" => "contact",
                        "type" => "phone",
                        "message" => "请填写正确格式手机号码",
                    ),
                ));
                $localId = $this->guid();
                $this->insertSqlData(array(
                    "table" => "lift_no_fly_zone",
                    "fieldList" => array("pic", "area", "name", "contact", "company", "begin_at", "expired_at", "url", "explain_text"),
                    "addItems" => array(
                        "applyUser_id" => $userId,
                        "local_ids" => $localId
                    )
                ));
                $this->returnSuccess("申请已提交");
            };
                break;
        }
    }

    public function getApprovingDataAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $userId = $this->getMonitorLoginUser()->userId;
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_LIST: {
                $tableName = "(SELECT L.* ,user.nickname FROM lift_no_fly_zone AS L
                                LEFT JOIN user ON L.applyUser_id=user.id)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "created_at" => "申请日期",
                    "name" => "申请项目名称",
                    "nickname" => "提交人",
                    "explain_text" => "说明",
                    "status" => "审批状态",
                    "notes" => "审批说明"
                ), $tableName, array(
                    ["name", "like", "%", "%"],
                    ["notes", "like", "%", "%"],
                    ["status", "=", "", ""],
                    ["created_at_start", ">=", "", "", "created_at"],
                    ["created_at_end", "<=", "", "", "created_at"],
                ), "created_at desc", "id");
            };
                break;
            case $this::REQUEST_ACTION_DETAIL: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "请求参数错误"),
                ));
                $keyId = $this->getPost("id");
                $sql = "SELECT L.* ,user.nickname FROM lift_no_fly_zone AS L
                          LEFT JOIN user ON L.applyUser_id=user.id
                          WHERE L.id=$keyId";
                $keyData = $this->fetchOne($sql);
                $this->returnJson($keyData);
            };
                break;
            case $this::REQUEST_ACTION_UPDATE: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "请选择ID",
                    ),
                ));
                $id = $this->getPost("id");
                $this->updateSqlData(array(
                    "table" => "lift_no_fly_zone",
                    "fieldList" => array("status", "notes",),
                    "addItems" => array("approvingUser_id" => $userId, "pushed" => "1"),
                    "where" => "id=$id"
                ));
                $data = $this->fetchOne("SELECT * FROM lift_no_fly_zone WHERE id=$id");
                $toUserId = $data["applyUser_id"];
                $pushMessage = "您在" . $data["created_at"] . "申请的" . "\"" . $data["name"] . "\"" . "飞行";
                switch($data["status"]){
                    case "0":
                        break;
                    case "2": {
                        $pushMessage = $pushMessage . "已通过";
                    };
                        break;
                    case "3": {
                        $pushMessage = $pushMessage . "被拒绝,差说明:" . $data["notes"];
                    };
                        break;
                    default:{
                        $this->returnError("审批状态异常");
                    };
                }
                $this->tcp_push(array(
                    "action" => "lift_check",
                    "status" => "2",
                    "data" =>array(
                        "id" => $data["id"],
                        "name" => $data["name"],
                        "area" => $data["area"],
                        "begin_at" =>$data["begin_at"],
                        "expired_at" => $data["expired_at"],
                        "status" => $data["status"],
                        "Notes" => $data["notes"],
                        "local_ids" => $data["local_ids"]
                    ),
                    "message" => $pushMessage
                ),$toUserId, $userId);
                $this->returnSuccess("审批成功");
            };
                break;
        }
    }

    public function filedItemChanged($table, $name, $value)
    {
        switch($name){
            case "status": {
                switch($value){
                    case "0":
                        return "已提交";
                        break;
                    case "2":
                        return "已通过";
                        break;
                    case "3":
                        return "拒绝";
                        break;
                }
            };
                break;
            case "explain_text":
            case "notes": {
                if($value == null){
                    return "";
                }
            };
                break;
        }
        return $value;
    }

    //haversin公式
    public function haversin($theta)
    {
        $value = sin($theta/2);
        return $value*$value;
    }
    //转换弧度
    public function convertDegressToRadians($degress)
    {
        return $degress * pi() / 180;
    }

    public function getLngLatDistance($postionX, $postionY)
    {
        //地球半径
        $earthRadius = 6371;
        //经纬度转换成弧度
        $lat1 = $this->convertDegressToRadians($postionX["lat"]);
        $lng1 = $this->convertDegressToRadians($postionX["lng"]);
        $lat2 = $this->convertDegressToRadians($postionY["lat"]);
        $lng2 = $this->convertDegressToRadians($postionY["lng"]);
        //差值
        $dLat = abs($lat1 - $lat2);
        $dLng = abs($lng1 - $lng2);
        //计算公式
        $h = $this->haversin($dLat) + cos($lat1) * cos($lat2) * $this->haversin($dLng);
        $distance = 2 * $earthRadius * asin(sqrt($h));
        return $distance;

    }




}